package com.xblibo.xruth.common;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.Assert;

import com.xblibo.xruth.exception.OtherException;


/**   
 * @Title: EntityDaoImpl.java
 * @Package com.tenement.dao.impl
 * @Description: TODO(添加描述)
 * @author libo
 * @date 2010-7-1 下午10:12:25    
 * @version V1.0   
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T,PK extends Serializable> extends SimpleHibernateDao<T, PK> implements BaseDao<T,PK> {
	
	public void deleteAll(Collection<T> entitys) throws OtherException {
		for(T entity:entitys){
			super.delete(entity);
		}
	}

	public List<T> findAll() throws OtherException {
		return super.getAll();
	}

	/**
	 * 按属性查找唯一对象,匹配方式为相等.
	 */
	public T findUniqueBy(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, value);
		return (T) createCriteria(criterion).uniqueResult();
	}

	/**
	 * 按id列表获取对象.
	 */
	public List<T> findByIds(List<PK> ids) {
		return find(Restrictions.in(getIdName(), ids));
	}
	

	public T findById(PK id) throws OtherException {
		return super.get(id);
	}

	public void saveOrUpdate(T entity) throws OtherException {
		super.save(entity);
	}

	public void saveOrUpdateAll(Collection<T> entitys) throws OtherException {
		for(T entity:entitys){
			super.save(entity);
		}
	} 
	
	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public <X> List<X> find(final String hql, final Object... values) {
		return super.find(hql, values);
	}

	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values 命名参数,按名称绑定.
	 */
	public <X> List<X> find(final String hql, final Map<String, ?> values) {
		return super.find(hql, values);
	}

	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public <X> X findUnique(final String hql, final Object... values) {
		return (X) super.findUnique(hql, values);
	}

	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values 命名参数,按名称绑定.
	 */
	public <X> X findUnique(final String hql, final Map<String, ?> values) {
		return (X) super.findUnique(hql, values);
	}

}
